/**
* gulp markdown 网页转换
*
**/
const through = require('through2')
var gutil = require('gulp-util');
var PluginError = gutil.PluginError
const PLUGIN_NAME = 'gulp-prefixer'
var marked = require('marked')
var highlight = require('highlight.js')
var yaml = require('yaml-front-matter')
var mustache = require('mustache')
var toc = require('markdown-toc');
var fs = require('fs')
var path = require('path')

function markdownToHtml (tpl, file) {
  let md = String(file.contents)
  var mate = yaml.loadFront(md)
  // 去掉mate
  md = md.replace(/^(-{3}(?:\n|\r)([\w\W]+?)(?:\n|\r)-{3})/, '')
  let markdownHtml = marked(md)
  // 如果模板是空的，则只输出解析内容
  if (tpl === '') {
    tpl = '{{{markdown}}}'
  }
  let html = ''
  mate.title = mate.title || path.basename(file.path, "ext")
  mate.markdown = markdownHtml
  // marked会encodeURI编码链接
  let tocMarkdown = decodeURI(toc(md).content)
  mate.toc = marked(tocMarkdown)
  // html = tpl.replace(/\{\{\W*markdown\W*\}\}/ig, markdownHtml)
  html = mustache.render(tpl, mate)
  return new Buffer(html)
}

function plugin(op) {
  var options = op || {}
  // throw new PluginError(PLUGIN_NAME, 'Missing prefix text!');
  var template = ''
  if (!!options.tplPath) {
    template = String(fs.readFileSync(options.tplPath, 'utf8'))
  }
  let renderer = new marked.Renderer()

  // renderer.heading = function (text, level) {
  //   // var escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');
  //   // return '<h' + level + ' id="' + new Buffer(text).toString('base64') + '">' + text + '</h' + level + '>';
  //   return '<h' + level + ' id="' + text.toLowerCase() + '">' + text + '</h' + level + '>';
  // }
  // renderer.listitem = (function (link) {
  //   console.log(link)
  //   let text = link.match(/<a .*?>(.*?)<\/a>/)
  //   return '<li><a href="'+ new Buffer(text[1]).toString('base64') +'">'+text[1]+'</a></li>'
  // })
  let markedOp = Object.assign({}, {renderer: renderer}, options.marked)
  marked.setOptions(markedOp)
  // 添加代码高亮
  marked.setOptions({
    highlight: function (code) {
      return highlight.highlightAuto(code).value
    }
  })

  function bufferContent (file, enc, cb) {
    if (file.isBuffer()) {
      file.contents = markdownToHtml(template, file)
      file.path = file.path.replace(/\.md/i, '.html')
    }
    this.push(file)
    // cb(null, file)
    cb()
  }
  function endBuffer () {
    // console.log('endBuffer')
  }
  return through.obj(bufferContent, endBuffer)
}

module.exports = plugin
